#include "stdafx.h"
#include "HLSLEffect.h"

#include "GlobalAppData.h"

using namespace mgfx;
using namespace mcore;

HLSLEffect::ResourceMap HLSLEffect::mResources = HLSLEffect::ResourceMap();

HLSLEffect * HLSLEffect::createFromFile(const std::string & fileName)
{
	ResourceMap::const_iterator found = mResources.find(fileName);
	if(found != mResources.end())
	{
		return found->second;
	}
	else
	{
		ID3DX11Effect * effect;
		std::string path = "content\\fx\\";
		path += fileName;

		//HANDLE hFile = CreateFile( path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
  //                             FILE_FLAG_SEQUENTIAL_SCAN, NULL );
		//if( INVALID_HANDLE_VALUE == hFile )
		//{
		//	//return E_FAIL;
		//}

		//LARGE_INTEGER FileSize;
		//GetFileSizeEx( hFile, &FileSize );

		//BYTE* pFileData = new BYTE[ FileSize.LowPart ];
		//if( !pFileData )
		//{
		//	//return E_OUTOFMEMORY;
		//}

		//DWORD BytesRead;
		//if( !ReadFile( hFile, pFileData, FileSize.LowPart, &BytesRead, NULL ) )
		//{
		//	//return E_FAIL; 
		//}

		//CloseHandle( hFile );

		DWORD shaderFlags = D3D10_SHADER_ENABLE_BACKWARDS_COMPATIBILITY;//D3D10_SHADER_ENABLE_STRICTNESS;
	#if defined( DEBUG ) || defined( _DEBUG )
		shaderFlags |= D3D10_SHADER_DEBUG;
		shaderFlags |= D3D10_SHADER_SKIP_OPTIMIZATION;
	#else
		shaderFlags |= D3D10_SHADER_OPTIMIZATION_LEVEL3;
	#endif
		
		ID3D10Blob *dataBlob = 0, *errorBlob = 0;
		HRESULT hr = D3DX11CompileFromFile(path.c_str(), NULL, NULL, NULL, "fx_5_0", shaderFlags, 0, NULL, &dataBlob, &errorBlob, NULL);
		if (FAILED(hr))
		{
			if( errorBlob )
			{
				MessageBoxA(0, (char*)errorBlob->GetBufferPointer(), 0, 0);
				ReleaseCOM(errorBlob);
			}
			DXTrace(__FILE__, (DWORD)__LINE__, hr, path.c_str(), true);
			return NULL;
		}
		
		HR(D3DX11CreateEffectFromMemory(dataBlob->GetBufferPointer(), dataBlob->GetBufferSize(), 0, GlobalAppData::Instance.Device, &effect));
		

		HLSLEffect * hlslEffect = new HLSLEffect;
		hlslEffect->mEffect = effect;
		mResources[fileName] = hlslEffect;
  
		return hlslEffect;
	}
}

void HLSLEffect::freeAll()
{
	ResourceMap::iterator itr, end = mResources.end();
	for(itr = mResources.begin() ; itr != end ; ++itr)
	{
		ReleaseCOM(itr->second->mEffect);
		delete itr->second;
	}
}

HLSLEffect::HLSLEffect()
{

}

HLSLEffect::~HLSLEffect()
{

}